<?php

class Pdb{
    private $dbh;
    private $dbhost;
    private $dbuser;
    private $dbpwd;
    private $dbname;
    
    public function __construct($dbhost, $dbuser, $dbpwd, $dbname){
        $this->dbhost = $dbhost;
        $this->dbuser = $dbuser;
        $this->dbpwd  = $this->dbpwd;
        $this->dbname = $dbname;
    }
    
    public function __get($name){
        if ($name == 'dbh'){
            $this->dbh = mysqli_connect($this->dbhost,$this->dbuser,$this->dbpwd, $this->dbname);
            mysqli_query($this->dbh, "SET names utf8");
			return $this->dbh;
        }
    }
    
    public function fetch($sql){
        $dbr =mysqli_query($this->dbh, $sql);
        $row = mysqli_fetch_assoc();
        mysqli_free_result($dbr);
        return $row;
    }
    
    public function fetch_col($sql){
        $dbr = mysqli_query($this->dbh, $sql);
        print mysqli_error($this->dbh);
        $row = mysqli_fetch_array($dbr);
        mysqli_free_result($dbr);
        return $row[0];
    }
    
    /**
     * 
     * @param string $sql
     */
    public function fetch_all($sql){
        $dbr = mysqli_query($this->dbh, $sql);
        $result = array();
        while ($row = mysqli_fetch_assoc($dbr)){
            $result[] = $row;
        }
        mysqli_free_result($dbr);
        return $result;
    }
    
    public function insert($sql){
        mysqli_query($this->dbh, $sql);
        return mysqli_insert_id($this->dbh);
    }
    
    public function replace($sql){
        mysqli_query($this->dbh, $sql);
        return mysqli_affected_rows($this->dbh);
    }
    
    public function del($sql){
        mysqli_query($this->dbh, $sql);
        return mysqli_affected_rows($this->dbh);
    }
}